export default {
	// 为当前模块开启命名空间
	namespaced: true,

	state: () => ({
		//购物车的数组，用于存储购物车中每个商品的信息对象
		//每个商品的信息对象，都包含如下六个属性
		//{goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),

	//模块的mutations方法
	mutations: {
		addToCart(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			// console.log(findResult);
			if (!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			// console.log(state.cart);
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		// 更新购物车中商品勾选状态
		updataGoodsState(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			findResult.goods_state = goods.goods_state
			this.commit('m_cart/saveToStorage')
		},
		// 更新购物车中商品数量
		updataGoodsNum(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			findResult.goods_count = goods.goods_count
			this.commit('m_cart/saveToStorage')
		},
		// 删除商品
		updataGoods(state, goods) {
			state.cart = state.cart.filter(x => x.goods_id !== goods.goods_id)
			this.commit('m_cart/saveToStorage')
		},
		//更新 购物车的图标
		setBadge(state, value) {
			//调用uni.setTabBarBadge()方法，为购物车设置右上角的徽标
			if (value === 0) {
				uni.removeTabBarBadge({
					index: 2
				})
			} else {
				uni.setTabBarBadge({
					index: 2, //索引
					text: value + '' //注意，text的值必须是字符串，不能是数字
				})
			}

			// console.log(value);
		},
		//将所有商品的勾选状态取反
		reverseSatate(state, newState) {
			state.cart.forEach(item => {
				item.goods_state = !newState
			})
			//持久化到本地
			this.commit('m_cart/saveToStorage')
		}
	},

	// 模块的getters属性
	getters: {
		// 商品的总数量
		total(state) {
			let c = 0
			state.cart.forEach(x => c = c + x.goods_count)
			return c
		},
		// 计算出已勾选的商品数量
		checkedCount(state) {
			//先使用filter方法，从购物车中购率已勾选的商品
			// 再使用reduce方法，将已勾选的商品数量进行累加
			// reduce()的返回值就是已勾选的商品总数量
			return state.cart.filter(x => x.goods_state).reduce((totle, item) => totle += item.goods_count, 0)
		},
		// 计算出已勾选的商品的总价格
		checkedPrice(state) {
			return state.cart.filter(x => x.goods_state).reduce((totle, item) => totle += item.goods_count * item
				.goods_price, 0).toFixed(2)
		},
		// 判断是否全部勾选
		allState(state) {
			return state.cart.every(item => item.goods_state)
		},
		//判断商品是否为空
		isNull(state) {
			if (state.cart.length === 0) {
				return true
			} else {
				return false
			}
		}
	}
}
